import PlatformUtil from "./PlatformUtil";
import NumberView from "./NumberView";
import allVariableJs from "./allVariable";
import httpUtils from "./XmlHttpTool";
import xorEncryptionData from "./Tool/xor";
cc.Class({

    extends: cc.Component,

    properties: {

        startGameBtn:cc.Button,
        numberCompontent:NumberView,
        energyCompontent:NumberView,
        bgMusicSound:{
            default: null,
            type: cc.AudioClip
        },
        topView:cc.Node,
        logonode:cc.Node,
        wordListView:cc.Node,
        friendListView:cc.Node,
        bageAllScrollView:cc.Node,
        inviteBtn:cc.Button,
        rankBtn:cc.Button,
        moreBtn:cc.Button,
        shopBtn:cc.Button,
        moreContentView:cc.Node,
        userEnergy:cc.Integer,
        showHubProjess:cc.Node,
        SvprogressPrefab: cc.Prefab,
        brannerAdmessage:"",
        videoBtn:cc.Button,
        chooseMarkView:cc.Node,
        taskBtn:cc.Button,
        gameBoxBtn:cc.Button,
        taskListView:cc.Node,
        taskContentListView:cc.Node,
        boxLayout:cc.Node,
        isOpenBox:cc.Boolean,
        taskThint:cc.Node,
        bageThink:cc.Node,
        moneytip:cc.Node


     
        
    },


    enterGameViewClick:function(){

        if(this.userEnergy>0){

            var changebig2 = cc.scaleTo(0.2,1.1);

            var finish = cc.callFunc(function(){
        
              var changesmail2 = cc.scaleTo(0.1,1.0);
              this.startGameBtn.node.runAction(changesmail2)
        
           }, this);
        
           var seq = cc.sequence(changebig2,finish)
        
            this.startGameBtn.node.runAction(seq)
    
            cc.director.loadScene("GameSence",function(){
    
                var mainNode= cc.find("Canvas/backgroundtop")
    
                mainNode.getComponent("backgrould").onAgainSence();
    
    
           });
        }else{

            this.chooseMarkView.active=true
            this.videoBtn.node.active=true
            // if(cc.isValid(this.showHubProjess)){
            //     this.showHubProjess.destroy();
            //   }
            //   this.showHubProjess = cc.instantiate(this.SvprogressPrefab);
            //   this.node.addChild(this.showHubProjess);
            //   this.showHubProjess.getComponent('SVProgressView').init("体力不足,无法开始游戏")
        
            //    let finish = cc.callFunc(() => { 
              
            //     this.showHubProjess.destroy();
            
            //   }, this);
            // let action = cc.sequence(cc.fadeIn(0.6), cc.delayTime(0.5), cc.fadeOut(1), finish);
            // this.showHubProjess.runAction(action);

        }
        

    },



    videoStartClick:function(){

        this.chooseMarkView.active=false
        this.videoBtn.node.active=false
        var _this=this
        if(allVariableJs.allvideoAD){

            allVariableJs.allvideoAD.offClose()
            allVariableJs.allvideoAD.offError()
            allVariableJs.allvideoAD.onClose(res => {
                if (res && res.isEnded || res === undefined) {
                  var that=this
                  httpUtils.httpPost("/marmot/ads_to_energy",{},function(res){
                      console.log("正常播放,可以发游戏奖励",res)
                      var flagstr=res.flag_key+PlatformUtil.platform.params["appver"]
                      var resultstr =xorEncryptionData.encryptionData(flagstr,PlatformUtil.platform.params)
                      httpUtils.NhttpPost("/marmot/ads_to_energy",{"flag_key":resultstr,"keysid":res.keysid},function(res){
                        console.log("广告体力请求接口",res)
                        that.energyCompontent.setText(parseInt(res["energy"]))
                        that.userEnergy=parseInt(res["energy"])
                    })         
                  })   
                } else {
                  // 播放中途退出，不下发游戏奖励
                  console.log("播放中途退出，不下发游戏奖d励",res)
                }
              })  

              allVariableJs.allvideoAD.onError((res) => {
          
                 let errcode=res["errCode"] 
                 _this.tishifinde()
                 if(errcode==1004){
                    console.log("无广告资源")
                 }else{
                    console.log("无广告资源")
                 }
              })

              allVariableJs.allvideoAD.load((res) => {
                console.log('激励视频 广告加载成功',res)
       
             })
             .then(() =>allVariableJs.allvideoAD.show())
             .catch(function(err){
                console.log('激励视频抓取结果',err) 
                _this.tishifinde()
             })

        }else{

            var that=this
            let rewardedVideoAd = wx.createRewardedVideoAd({

                adUnitId: 'adunit-8536f460f8a4925c'
            
            })
            allVariableJs.allvideoAD=rewardedVideoAd
            allVariableJs.allvideoAD.offClose()
            allVariableJs.allvideoAD.onClose(res => {
                if (res && res.isEnded || res === undefined) {
                  var that=this
                  httpUtils.httpPost("/marmot/ads_to_energy",{},function(res){
                      console.log("正常播放,可以发游戏奖励",res)
                      var flagstr=res.flag_key+PlatformUtil.platform.params["appver"]
                      var resultstr =xorEncryptionData.encryptionData(flagstr,PlatformUtil.platform.params)
                      httpUtils.NhttpPost("/marmot/ads_to_energy",{"flag_key":resultstr,"keysid":res.keysid},function(res){
                        console.log("广告体力请求接口",res)
                        that.energyCompontent.setText(parseInt(res["energy"]))
                        that.userEnergy=parseInt(res["energy"])
                    })         
                  })   
                } else {
                  // 播放中途退出，不下发游戏奖励
                  console.log("播放中途退出，不下发游戏奖d励",res)
                }
              })  

              allVariableJs.allvideoAD.onError((res) => {
          
                 let errcode=res["errCode"] 
                 that.tishifinde()
                 if(errcode==1004){

                    console.log("无广告资源")
                 }else{
                    console.log("无广告资源")

                 }
              })
              allVariableJs.allvideoAD.load((res) => {
                console.log('激励视频 广告加载成功',res)
       
             })
             .then(() =>allVariableJs.allvideoAD.show())
             .catch(function(err){
                console.log('激励视频抓取结果',err) 
                that.tishifinde()
             })
        }
    },


     tishifinde:function(){
   
        if(cc.isValid(this.showHubProjess)){
        this.showHubProjess.destroy();
        }
        this.showHubProjess = cc.instantiate(this.SvprogressPrefab);
        this.node.addChild(this.showHubProjess);
        this.showHubProjess.getComponent('SVProgressView').init("今天的广告已经看完了哦！")

        let finish = cc.callFunc(() => { 

        this.showHubProjess.destroy();

        }, this);
        let action = cc.sequence(cc.fadeIn(0.6), cc.delayTime(3), cc.fadeOut(1), finish);
        this.showHubProjess.runAction(action);
     },


    onLoad () {

        var that =this

        cc.loader.load({url: "https://h5.taoqi001.com/minigames/mouse_click/mouseImage/invites.png", type: 'png'}, function (err, img) {
          var mylogo  = new cc.SpriteFrame(img); 
  
          that.inviteBtn.node.getComponent(cc.Sprite).spriteFrame = mylogo;
    
        });
        
        let system = wx.getSystemInfoSync();
        let width = system.screenWidth;
        let height = system.screenHeight;

        this.isOpenBox=false

        console.log("屏幕宽与高", width,height);
        PlatformUtil.init();

        PlatformUtil.platform.init(this);

        PlatformUtil.platform.getStorage("wxtoken")

        window["httppost"]=httpUtils;

        console.log("全局",window["httppost"])
        
        console.log("取出缓存的token",PlatformUtil.platform.getStorage("wxtoken"))

        this.getUserInfoMessage()

         if(PlatformUtil.platform.getStorage("wxtoken")){

            PlatformUtil.platform.checkSession();

         }else{
            console.log("第一次登录")
            this.loginGame();

         }

        PlatformUtil.platform.loadSuccess();
   
        if(allVariableJs.isMusicPlaying){


        }else{
           
            var isSwitchSound=PlatformUtil.platform.enableBGM()

            console.log("设备类型",cc.sys.os)
         
            switch (cc.sys.os){
                case cc.sys.OS_ANDROID:
                if(isSwitchSound){
                    this.current = cc.audioEngine.play(this.bgMusicSound, true, 1);
                }
                break;
                case cc.sys.OS_IOS:
                this.current = cc.audioEngine.play(this.bgMusicSound, true, 1);
                 break;
    
                 default:
                 this.current = cc.audioEngine.play(this.bgMusicSound, true, 1);
                 break;
    
            } 

            allVariableJs.isMusicPlaying=true
        }
      
         
        console.log("播放后的音频",this.current)

        this.isIphoneX=PlatformUtil.platform.isFullScreen()

        this.logonode.active=true

        var that = this

        cc.loader.load({url: "https://h5.taoqi001.com/upload/201901/b0b9b7ee3b07972bd1d309c7e38eb9cc67e28ff7.png", type: 'png'}, function(err,img){

            var mylogo  = new cc.SpriteFrame(img); 

            that.logonode.getComponent(cc.Sprite).spriteFrame = mylogo;
 
        });

        var changebig2 = cc.scaleTo(0.2,1.2);

        var finish = cc.callFunc(function(){

        var changesmail2 = cc.scaleTo(0.1,1.0);
        this.logonode.runAction(changesmail2)

    }, this);

     var seq = cc.sequence(changebig2,finish)

     this.logonode.runAction(seq)

        if(height==812){

         
        }else{
    
        var that =this
        cc.loader.load({url: "https://h5.taoqi001.com/upload/201812/51308ffe7e23853bfd178b290cb53ab9c7ec6128.jpg", type: 'png'}, function (err, img) {

            var mylogo  = new cc.SpriteFrame(img); 

            that.node.getComponent(cc.Sprite).spriteFrame = mylogo;
          that.node.height=1624
        
        });

        that.topView.y=607
        this.logonode.y=200
    } 

    
   if(allVariableJs.allbrannerAD){
    console.log("不要创建branner广告了")
 
   }else{

    let bannerAd = wx.createBannerAd({
        adUnitId: 'adunit-d7f07be21319bd0b',
        style: {
            left: 0,
            top: 0,
            width: width
        }
    })

    bannerAd.onResize(res => {

        console.log("广告位置",res.width, res.height)
        bannerAd.style.top=height-res.height
        bannerAd.style.left=0
        bannerAd.style.width=width
    
     })
     allVariableJs.allbrannerAD=bannerAd
     allVariableJs.allbrannerAD.onError((res) => {
          
        console.log('广告错误',res)
    
    })
   }
   
   allVariableJs.allbrannerAD.show()

   var animState =this.moneytip.getComponent(cc.Animation)
   
   animState.playAdditive("tips");

    var animtip =animState.getAnimationState('tips');
  
    // // 设置循环模式为 Loop
    animtip.wrapMode = cc.WrapMode.Loop;
  
    // 设置动画循环次数为无限次
    animtip.repeatCount = Infinity;
  
    },

    loginGame:function(){

        var _this= this
        
        PlatformUtil.platform.getWeXinToken(function(rescode){
            
            httpUtils.getTokenPost("/users/wxregister",{"regtype":1,"code":rescode},function(res){

                console.log("获取token请求",res)
               
                PlatformUtil.platform.setStorage({'key':"wxtoken",'value':res["token"]})

                PlatformUtil.platform.getWeXinUserInfo(function(userInfo){

                    console.log("传过来的用户信息",userInfo)

                })

                _this.loginMouse();
            })
            
       })
    },

    taskClick:function(){


        var changebig2 = cc.scaleTo(0.2,1.1);

    var finish = cc.callFunc(function(){

      var changesmail2 = cc.scaleTo(0.1,1.0);
      this.taskBtn.node.runAction(changesmail2)

   }, this);

    var seq = cc.sequence(changebig2,finish)

    this.taskBtn.node.runAction(seq)

    this.taskListView.active=true
    this.taskContentListView.getComponent("taskScrollview").init()
    },


    gameBoxClick:function(){


          if(this.isOpenBox==false){
              this.boxLayout.active=true
              this.boxLayout.getComponent("boxLayout").init()
              this.isOpenBox=true
          }else{
              this.boxLayout.active=false
              this.isOpenBox=false
          }

        var changebig2 = cc.scaleTo(0.2,1.1);

        var finish = cc.callFunc(function(){

           var changesmail2 = cc.scaleTo(0.1,1.0);
          this.gameBoxBtn.node.runAction(changesmail2)
      

        }, this);

       var seq = cc.sequence(changebig2,finish)

      this.gameBoxBtn.node.runAction(seq)

        // if(cc.isValid(this.showHubProjess)){
        //     this.showHubProjess.destroy();
        //   }
        //   this.showHubProjess = cc.instantiate(this.SvprogressPrefab);
        //   this.node.addChild(this.showHubProjess);
        //   this.showHubProjess.getComponent('SVProgressView').init("暂未开放,敬请期待...")
    
        //    let finish = cc.callFunc(() => { 
          
        //     this.showHubProjess.destroy();
        //   }, this);
        // let action = cc.sequence(cc.fadeIn(0.6), cc.delayTime(0.5), cc.fadeOut(1), finish);
        // this.showHubProjess.runAction(action);


         

    },

    getUserInfoMessage:function(){

       var that= this
        httpUtils.NhttpPost("/marmot/user_info",{},function(res){

            console.log("用户信息",res)
            
            var stars =parseInt(res["ticket_num"])
            var energy=parseInt(res["energy_num"])
            if(parseInt(res["wechat_money"])>=10){
                that.bageThink.active=true
            }
            that.userEnergy=energy
            that.numberCompontent.setText(stars)
            that.energyCompontent.setText(energy)

        })  

        httpUtils.NhttpPost("/users/login",{},function(res){

            console.log("送体力",res)
        })  

    },

    loginMouse:function(){

        console.log("确认的字典",PlatformUtil.platform.params)
        this.getUserInfoMessage()
        this.notifyPrize()
        this.startGameBtn.node.active=true
        this.topView.getChildByName("scoreShow").active=true
        // this.topView.getChildByName("chargeBtn").active=true
        this.node.getChildByName("shopBtn").active=true

       
    },

    notifyPrize:function(){

      var that= this
       httpUtils.NhttpPost("/marmot/notify_prize",{},function(res){

        console.log("未领奖任务",res)
        if(res==true){
            that.taskThint.active=true
        }else{
            that.taskThint.active=false  
        }
       }
       )
    },

    refreCoinClick:function(){

    //     var that= this
    //    httpUtils.NhttpPost("/users/stars",{},function(res){

    //     var stars =parseInt(res["stars"])
      
    //     that.numberCompontent.setText(stars)
  
    //    },function(failres){
    //     console.log('刷新金币错误',failres)
    //    }
    //    )

},

  inviteShare:function(){

    console.log("邀请好友一起玩")
   allVariableJs.iswatchAd=false
      var that= this
       httpUtils.NhttpPost("/wxmp/marmot/share_msg",{},function(res){

        console.log('分享成功',res)

     var changebig2 = cc.scaleTo(0.2,1.1);

      var finish = cc.callFunc(function(){

      var changesmail2 = cc.scaleTo(0.1,1.0);
      that.inviteBtn.node.runAction(changesmail2)
      PlatformUtil.platform.wxShareMessage(res,function(sharessmessage){
        console.log("最多加三个体力",sharessmessage)

        if(cc.isValid(that.showHubProjess)){
            that.showHubProjess.destroy();
          }
          that.showHubProjess = cc.instantiate(that.SvprogressPrefab);
          that.node.addChild(that.showHubProjess);
          that.showHubProjess.getComponent('SVProgressView').init(sharessmessage["tip"])
    
           let finish = cc.callFunc(() => { 
          
            that.showHubProjess.destroy();
        
          }, that);
        let action = cc.sequence(cc.fadeIn(0.6), cc.delayTime(0.5), cc.fadeOut(1), finish);
        that.showHubProjess.runAction(action);

      });

   }, that);

    var seq = cc.sequence(changebig2,finish)

    that.inviteBtn.node.runAction(seq)

  
       },function(failres){
   
       }
       )


  },

  rankView:function(){

    console.log("排行榜");
  
    var changebig2 = cc.scaleTo(0.2,1.1);

    var finish = cc.callFunc(function(){

      var changesmail2 = cc.scaleTo(0.1,1.0);
      this.rankBtn.node.runAction(changesmail2)
      this.friendListView.active=true

   }, this);

    var seq = cc.sequence(changebig2,finish)

    this.rankBtn.node.runAction(seq)

  },

  bageView:function(){

    console.log("兑换包裹");
  },

  moreView:function(){

    console.log("更多");
    
    var changebig2 = cc.scaleTo(0.2,1.1);

    var finish = cc.callFunc(function(){

      var changesmail2 = cc.scaleTo(0.1,1.0);
      this.moreBtn.node.runAction(changesmail2)
      this.moreContentView.getComponent("bageScrollView").init()
      this.bageAllScrollView.active=true

   }, this);

    var seq = cc.sequence(changebig2,finish)

    this.moreBtn.node.runAction(seq)

  },
  
    start () {

    },

});
